﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace ProjectSemIII.Administrator.Survey
{
    public partial class EditSurvey : System.Web.UI.Page
    {
        private List<Entity.SurveyCatalog> listSurveyCatalog;
        private SurveyProcess surveyProcess;
        private Entity.Survey sv;
        private int dateStart;
        private int surveyID;
        private string imageUrl;
        private const bool blnAllowPaging = true;
        private const int iPageSize = 5;
        private static PagedDataSource pgdProducts;
        private List<Entity.Question> listQuestion;
        protected void Page_Load(object sender, EventArgs e)
        {
            surveyProcess = new SurveyProcess();
            if (Request.QueryString.Count == 1)
            {
                if (Request.QueryString.Keys[0].ToString() == "surveyid")
                {
                    surveyID = Convert.ToInt32(Request.QueryString["surveyid"].ToString());
                    pgdProducts = new PagedDataSource();
                    if (!Page.IsPostBack)
                    {
                        this.renderSurveyInfo();
                        this.getAllQuestion();
                    }
                }
                else
                {
                    Response.Redirect("/404.html");
                }
            }
            else
            {
                Response.Redirect("/404.html");
            }
        }

        protected void ddSurveyCatalog_SelectedIndexChanged(object sender, EventArgs e)
        {
            DropDownList ddl = (DropDownList)sender;
            spanCatalogName.InnerText = ddl.SelectedItem.Text;
        }

        protected void ddPlayer_SelectedIndexChanged(object sender, EventArgs e)
        {
            DropDownList ddl = (DropDownList)sender;
            idGroup.InnerText = ddl.SelectedItem.Text;
        }

        protected void startDate_SelectionChanged(object sender, EventArgs e)
        {
            deadLine.SelectedDate = startDate.SelectedDate.AddDays(1);
            TimeSpan sp = startDate.SelectedDate.Subtract(DateTime.Now.Date);
            dateStart = sp.Days;
        }

        protected void deadLine_DayRender(object sender, DayRenderEventArgs e)
        {
            if (e.Day.Date.CompareTo(DateTime.Today.AddDays(dateStart + 1)) < 0)
            {
                e.Day.IsSelectable = false;
            }
        }

        protected void startDate_DayRender(object sender, DayRenderEventArgs e)
        {
            if (e.Day.Date.CompareTo(DateTime.Today) < 0)
            {
                e.Day.IsSelectable = false;
            }
        }

        protected void submitEdit_Click(object sender, EventArgs e)
        {
            this.updateSurveyInfo();
        }


        private void updateSurveyInfo()
        {
            Entity.Survey s = new Entity.Survey();
            s.SurveyID = surveyID;
            s.CatalogID = Convert.ToInt32(ddSurveyCatalog.SelectedValue);
            s.SurveyName = txtSurveyName.Text;
            s.SurveyDesc = txtSurveyDesc.Text;
            s.SurveyPlayer = Convert.ToInt32(ddPlayer.SelectedValue);
            if (fuImages.HasFile)
            {
                try
                {
                    s.SurveyImage = fuImages.PostedFile.FileName;
                    fuImages.SaveAs(System.Web.HttpContext.Current.Server.MapPath("~/Images/Surveys/" + fuImages.FileName));
                }
                catch
                {
                    s.SurveyImage = fuImages.PostedFile.FileName;
                }
            }
            else
            {
                this.renderSurveyInfo();
                s.SurveyImage = imageUrl;
            }
            s.SurveyStartDate = startDate.SelectedDate;
            s.SurveyDateLine = deadLine.SelectedDate;
            int result = surveyProcess.updateSurveyInfo(s.SurveyID, s.SurveyName, s.SurveyDesc, s.SurveyImage, s.SurveyStartDate, s.SurveyDateLine, s.CatalogID, s.SurveyPlayer);
            if (result == 10)
            {
                lbError.Text = "Edit survey successful!";
                this.renderSurveyInfo();
            }
            else
            {
                lbError.ForeColor = System.Drawing.Color.Red;
                lbError.Text = "Error in update process!";
                this.renderSurveyInfo();
            }
        }
        private void renderSurveyInfo()
        {
            this.getAllSurveyCatalog();
            sv = surveyProcess.getSurveyByID(surveyID);
            startDate.SelectedDate = sv.SurveyStartDate;
            deadLine.SelectedDate = sv.SurveyDateLine;
            ddSurveyCatalog.SelectedValue = sv.CatalogID.ToString();
            spanCatalogName.InnerText = ddSurveyCatalog.SelectedItem.Text;
            txtSurveyName.Text = sv.SurveyName;
            txtSurveyDesc.Text = sv.SurveyDesc;
            ddPlayer.SelectedValue = sv.SurveyPlayer.ToString();
            imageUrl = sv.SurveyImage;
            idGroup.InnerText = ddPlayer.SelectedItem.Text;
            imageSurvey.ImageUrl = "~/Images/Surveys/" + sv.SurveyImage;
        }
        private void getAllSurveyCatalog()
        {
            listSurveyCatalog = new List<Entity.SurveyCatalog>();
            Entity.SurveyCatalog sc = new Entity.SurveyCatalog();
            sc.CatalogName = "Select Catalog Name";
            sc.CatalogID = -1;
            listSurveyCatalog.Add(sc);
            foreach (Entity.SurveyCatalog esc in surveyProcess.getAllSurveyCatalog())
            {
                listSurveyCatalog.Add(esc);
            }
            ddSurveyCatalog.DataSource = listSurveyCatalog;
            ddSurveyCatalog.DataTextField = "CatalogName";
            ddSurveyCatalog.DataValueField = "CatalogID";
            ddSurveyCatalog.DataBind();
        }

        protected void btPrev_Click(object sender, EventArgs e)
        {
            LinkButton lbuton = (LinkButton)sender;
            if (lbuton.ID == "btPrev")
            {
                if (ThisPageNumber > 0)
                {
                    ThisPageNumber = ThisPageNumber - 1;
                    this.getAllQuestion();
                }
            }
            //Change page when user click to next number button
            else if (lbuton.ID == "btNext")
            {
                if (ThisPageNumber < totalPage.Items.Count - 1)
                {
                    ThisPageNumber = ThisPageNumber + 1;
                    this.getAllQuestion();
                }
            }
        }

        protected void PageNumber_Click(object sender, EventArgs e)
        {
            LinkButton lbuton = (LinkButton)sender;
            ThisPageNumber = Convert.ToInt32(lbuton.Text) - 1;
            this.getAllQuestion();
        }

        protected void allQuestion_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            int idQuestion = Convert.ToInt32(e.CommandArgument);
            if (e.CommandName == "Delete")
            {
                int result = surveyProcess.deleteQuestionByID(idQuestion);
                if (result == 10)
                {
                    lbError.Text = "Delete question successful!";
                    this.getAllQuestion();
                }
                else
                {
                    lbError.ForeColor = System.Drawing.Color.Red;
                    lbError.Text = "Error in delete process!";
                }
            }
            else if (e.CommandName == "Edit")
            {
                ClientScript.RegisterStartupScript(GetType(), "openEditSurveyPage", "window.open('QuestionManage.aspx?questionid=" + idQuestion + "');", true);
            }
        }

        private void getAllQuestion()
        {
            listQuestion = surveyProcess.getAllQuestionBySurveyID(surveyID);

            pgdProducts.AllowPaging = blnAllowPaging;
            pgdProducts.PageSize = iPageSize;
            pgdProducts.DataSource = listQuestion;

            pgdProducts.CurrentPageIndex = ThisPageNumber;
            fillTotalPage(pgdProducts.PageCount);

            allQuestion.DataSource = pgdProducts;
            allQuestion.DataBind();
        }

        private void fillTotalPage(int iTotalPages)
        {
            List<int> pageID = new List<int>();
            for (int i = 1; i <= iTotalPages; i++)
            {
                pageID.Add(i);
            }
            totalPage.DataSource = pageID;
            totalPage.DataBind();
        }

        private int ThisPageNumber
        {
            get
            {
                object obj = ViewState["ThisPageNumber"];
                return (obj == null) ? 0 : (int)obj;
            }
            set
            {
                this.ViewState["ThisPageNumber"] = value;
            }
        }

        protected void createQuestion_Click(object sender, EventArgs e)
        {
            ClientScript.RegisterStartupScript(GetType(), "openEditSurveyPage", "window.open('QuestionManage.aspx?surveyid=" + surveyID + "');", true);
        }
    }
}